<?php
namespace Model;

use Lib\Http\Request;

class Net {
	const HOST = '192.168.1.1';
	const USERNAME = 'admin';
	const PASSWORD = 'admin';

	public function __construct() {}

	public function info() {
		$url = 'http://' . self::USERNAME . ':' . self::PASSWORD . '@' . self::HOST . '/userRpm/StatusRpm.htm';
		
		try {
			$html = $this->http($url);
		} catch (\Exception $e) {
			return [];
		}
		
		preg_match('/wanPara = new Array\((.+)\);/sU', $html, $x);
		
		$info = json_decode('[' . $x[1] . ']');
		if (!isset($x[1])) {
			return [];
		}
		
		return array('ip' => $info[2]);
	}

	public function connect() {
		$url = 'http://' . self::USERNAME . ':' . self::PASSWORD . '@' . self::HOST . '/userRpm/StatusRpm.htm?Connect=%C1%AC%20%BD%D3&wan=1';
		
		try {
			$html = $this->http($url);
		} catch (\Exception $e) {
			return FALSE;
		}
		
		return TRUE;
	}

	public function disconnect() {
		$url = 'http://' . self::USERNAME . ':' . self::PASSWORD . '@' . self::HOST . '/userRpm/StatusRpm.htm?Disconnect=%B6%CF%20%CF%DF&wan=1';
		
		try {
			$html = $this->http($url);
		} catch (\Exception $e) {
			return FALSE;
		}
		
		return TRUE;
	}

	private function http($url) {
		static $Request = NULL;
		is_null($Request) && $Request = new Request();
		
		$Request->option(Request::OPT_MODE, Request::OPT_MODE_SOCKET);
		$Request->option(Request::OPT_TIMEOUT, 5);
		$Request->option(Request::OPT_READ_TIMEOUT, 10);
		
		// ======================================================
		$Response = $Request->get($url);
		if (!is_object($Response) || $Response->status() != '200') {
			throw new \Exception('HTTP Fail.');
		}
		
		return $Response;
	}
}